package org.nidy.erp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.nidy.erp.config.WebAppConfigurer;
import org.nidy.erp.pojo.Goods;
import org.nidy.erp.service.IBigHomeMiniProgrameService;
import org.nidy.erp.service.IGoodsService;
import org.nidy.erp.utils.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.File;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@Service("bigHomeMiniProgrameService")
public class BigHomeMiniProgrameService implements IBigHomeMiniProgrameService {
    String directoryPath = WebAppConfigurer.swiper_IMAGE_PATH;
    String bigTypePath = WebAppConfigurer. bigType_IMAGE_PATH;
    @Autowired
    private IGoodsService iGoodsService;
    @Override
    public ResponseResult getSwiperList() {
        File directory = new File(directoryPath);
        if (!directory.exists() || !directory.isDirectory()) {
            return ResponseResult.error("目录不存在");
        }
        // 获取目录下所有文件名
        List<String> fileList = Arrays.stream(Objects.requireNonNull(directory.listFiles()))
                .map(File::getName)
                .collect(Collectors.toList());
        // 构造可访问的 URL 前缀
        String baseUrl = WebAppConfigurer.swiper_subUrl_PATH;
        // 拼接完整 URL 列表
        AtomicInteger index = new AtomicInteger(0);
        List<Map<String, Object>> fileUrls = fileList.stream()
                .map(fileName -> {
                    Map<String, Object> map = new HashMap<>();
                    map.put("id", index.getAndIncrement()+1);
                    map.put("filename", baseUrl+fileName);
                    return map;
                })
                .collect(Collectors.toList());
        return ResponseResult.success(fileUrls);
    }

    @Override
    public List<Map<String, Object>> getBigTypeList() {
        String bigTypeSubUrl = WebAppConfigurer.bigType_subUrl_PATH;
        File bigTypeDictory = new File(bigTypePath);
        if (!bigTypeDictory.exists() || !bigTypeDictory.isDirectory()) {
            return null;
        }
        List<String> bigTypeCollect = Arrays.stream(bigTypeDictory.listFiles()).map(File::getName).collect(Collectors.toList());
        List<Map<String, Object>> bigTypeUrlList = bigTypeCollect.stream().map(fileName -> {
            String idStr = fileName.split("\\.")[0];
            int id = 0;
            try {
                id = Integer.parseInt(idStr);
            } catch (NumberFormatException e) {
                id=-1;
            }
            Map<String, Object> map = new HashMap<>();
            map.put("id", id);
            map.put("fileName", bigTypeSubUrl + fileName);
            return map;
        }).collect(Collectors.toList());
        return bigTypeUrlList;
    }

    @Override
//    public List<Map<String, Object>> getGoodsList() {
//        Map<String, Object> goodsMap = new HashMap<>();
//        List<Goods> goodsList = iGoodsService.getGoodsList();
//        List<Map<String, Object>> result = goodsList.stream().map(goods -> {
//            Integer goodsClassId = Integer.parseInt(goods.getItemClass().split("_")[1]);
//            goodsMap.put("goodsClassId", goodsClassId);
//            goodsMap.put("goodsList", goods);
//            return goodsMap;
//        }).collect(Collectors.toList());
//        return result;
//    }
    public List<Map<String, Object>> getGoodsList() {
        List<Goods> goodsList = iGoodsService.getGoodsList();
        // 用以存储按 goodsClassId 分组的结果
        Map<Integer, Map<String, Object>> groupedResult = new HashMap<>();

        for (Goods goods : goodsList) {
            try {
                String[] itemClassParts = goods.getItemClass().split("_");
                Integer goodsClassId = Integer.parseInt(itemClassParts[1]);

                // 如果不存在该 goodsClassId 的类别，则新建一个 Map 并放入列表
                if (!groupedResult.containsKey(goodsClassId)) {
                    Map<String, Object> goodsGroup = new HashMap<>();
                    goodsGroup.put("goodsClassId", goodsClassId);
                    goodsGroup.put("goodsList", new ArrayList<Goods>());
                    groupedResult.put(goodsClassId, goodsGroup);
                }

                // 将当前商品添加到对应的类别中
                @SuppressWarnings("unchecked")
                List<Goods> list = (List<Goods>) groupedResult.get(goodsClassId).get("goodsList");
                list.add(goods);
            } catch (Exception e) {
                // 忽略格式不正确的条目或其他异常
                continue;
            }
        }

        // 返回结果列表
        return new ArrayList<>(groupedResult.values());
    }

}
